// pages/driver/order_detail/order_detail.js
var Tool = require("../../../utils/ztool.js");
var util = require('../../../utils/util.js');
var tool = new Tool();
Page({
  data: {
    IDD: '',
    //订单错误标识
    order_error: false,
    winHeight: 0,
    orderDetail:'',
    caranddriver: [],
    carname: [],
    UseCarStart: '',
    UseCarEnd: '',
    telNum: '',
    chengkedetail:[],
  },

  callphone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.id //仅为示例，并非真实的电话号码
    });
  },

  //推送方法
  PushTo: function (status) {
    var that = this
    var cont = ''
    var cont2 = ''
    if (status == 0) {
      cont = '司机接受了您的订单'
      cont2 = '订单已接受'
    }
    if (status == 3) {
      cont = '司机拒绝了您的订单'
      cont2 = '订单已拒绝'
    }
    wx.showToast({
      title: '正在加载...',
      icon: 'loading',
      duration: 10000
    });
    console.log(that.data.telNum)
    wx.request({
      url: 'https://www.lanshuicar.com/Server/Weixin/WxPushHdl.ashx',
      data: {
        idd: that.data.IDD,
        tel: that.data.telNum,
        title: cont,
        content: cont2,
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        // var data = tool.getRegularJson(res.data);
        var code = res.data.code;
        console.log(res);
        if (code == 0) {
          console.log('post推送请求成功')

        } else {
          console.log(res)
        }
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function () {
        // complete
        wx.hideToast();
        wx.stopPullDownRefresh();//当处理完数据刷新后，wx.stopPullDownRefresh可以停止当前页面的下拉刷新。
      }
    })
  },



  onLoad: function (options) {
    var that = this;
    // 页面初始化 options为页面跳转所带来的参数
    var IDD1 = options.IDD;
    this.setData({
      IDD: IDD1
    });

    if (!IDD1) {
      this.setData({
        order_error: true
      });
    } else {
      //请求加载订单数据
      getServiceData(this);
      //请求加载车辆数据
      getCarandDriver(this);
      //获取乘客数据
      getDataChengke(this);
    }

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winHeight: res.windowHeight
        });
      }
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },

  //下拉加载
  onPullDownRefresh: function () {
    getServiceData(this);
  },

  locateChengke: function (e) {
    var that = this
    var open = e.currentTarget.dataset.open
    // console.log(that.data.dateEnd)
    var time1 = util.formatTime1(new Date())
    console.log(time1)
    if (that.data.orderDetail.UseCarEndTime < time1) {
      that.showError('订单已过期')
      return
    }
    if (open == '0' || open=='') {
      that.showError('此乘客尚未开启定位功能')
      return
    }
    var driverID = e.currentTarget.id
    wx.navigateTo({
      url: '../../travelAgency/locate?IDD=' + that.data.IDD + '&DriverID=' + driverID + '&retype=5',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  goPassenger: function () {
    if (this.data.orderDetail.cgsSee == 1) {
      if (this.data.orderDetail.sjSee == 1) {
        wx.navigateTo({
          url: '../passengers/passengers?IDD=' + this.data.orderDetail.IDD + '&endtime=' + this.data.orderDetail.UseCarEndTime,
        })
      } else {
        wx.showModal({
          content: '不允许查看乘客信息，请联系车公司!',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {

            }
          }
        });
      }
    } else {
      wx.showModal({
        content: '不允许查看乘客信息，请联系旅行社',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {

          }
        }
      });
    }
  },

  operateOrder: function (e) {
    var that = this;
    var msgs = '';
    var userInfo = wx.getStorageSync('userInfo');
    var userType = wx.getStorageSync('userType');
    console.log(e);
    var id = e.currentTarget.id;
    var status;
    if (id == 'accept') {
      status = 0;
      msgs = '您确定要接受此订单吗？';
    } else if (id == 'reject') {
      status = 3;
      msgs = '您确定要拒绝此订单吗？';
    }

    wx.showModal({
      // title:"蓝水软件范文伟",
      content: msgs,
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        console.log(res.confirm)
        if (res.confirm) {
          wx.request({
            url: 'https://www.lanshuicar.com/Server/RefuseorReOrder.ashx',
            data: {
              IDD: that.data.IDD,
              ID: userInfo.Id,
              status: status,
              Type: userType
            },
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // header: {}, // 设置请求的 header
            success: function (res) {
              console.log(res.data)
              // success
              var code = res.data.code;
              if (code == 0) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'success',
                  duration: 2000
                });
                that.PushTo(status)
                getServiceData(that)

                var pages = getCurrentPages()
                var backpage = pages[pages.length - 2]
                backpage.setData({
                  backtag: 1,
                });

              }
            },
            fail: function () {
              // fail
            },
            complete: function () {
              // complete
            }
          })
        }
      }
    });
  },

  showError: function (msg) {
    var that = this;
    that.setData({
      formError: true,
      errorMessage: msg
    });

    setTimeout(function () {
      that.setData({
        formError: false,
        errorMessage: '未知错误'
      });
    }, 2000);
  },

  bindRetry: function () {

    this.setData({
      order_error: false
    });

    //请求加载订单数据
    getServiceData(this);
    //请求加载车辆数据
    getCarandDriver(this);
  }

})

function getCarandDriver(that) {
  that.setData({
    caranddriver: [],
  });
  var userInfo = wx.getStorageSync('userInfo');
  wx.request({
    url: 'https://www.lanshuicar.com/Server/DriverPerson/GetDriverCarInfo.ashx',
    data: {
      Idd: that.data.IDD,
      ID: userInfo.Id,
      type: 1,
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      if (res.statusCode == 404) {
        //接口加载失败
        console.log('加载接口错误');
        //隐藏Toast
        wx.hideToast();
        //显示错误信息
        that.showError('车辆信息接口请求失败，请重试')
        that.setData({
          carname: '车辆数据获取有误'
        });

        return
      }
      var data = tool.getRegularJson(res.data);
      var code = data.code;
      console.log(data);

      if (code == 0) {
        that.setData({
          caranddriver: that.data.caranddriver.concat(data.data),
        });
        console.log(that.data.caranddriver)
        getusecar(that)
      }
    },
    fail: function () {
      // fail
    },
    complete: function () {
      // complete
    }
  })
}

function getusecar(that) {
  var userInfo = wx.getStorageSync('userInfo');
  console.log('bbbbbbbbbbbbbbbbbbbbbbbbbbb',userInfo)
  var array = []
  for (var i = 0; i < that.data.caranddriver.length; i++) {
    if (that.data.caranddriver[i].DriverID == userInfo.Id) {
      array.push(that.data.caranddriver[i].CarName)
        // carname: that.data.caranddriver[i].CarName
     
    }
  }
  that.setData({
    carname: array
  });
}

function getServiceData(that) {
  wx.showToast({
    title: '正在加载...',
    icon: 'loading',
    duration: 10000
  });
  var userInfo = wx.getStorageSync('userInfo');
  wx.request({
    url: 'https://www.lanshuicar.com/Server/DriverPerson/DriverOrders.ashx',
    data: {
      Idd: that.data.IDD,
      ID: userInfo.Id
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      console.log(res)
      // success
      if (res.statusCode == 404) {
        //接口加载失败
        console.log('加载接口错误');
        //隐藏Toast
        wx.hideToast();
        //显示错误信息
        that.showError('接口请求失败，请重试')
        that.setData({
          order_error: true
        });

        return
      }
      var data = tool.getRegularJson(res.data);
      var code = data.code;
      console.log(res);
      if (code == 0) {
        that.setData({
          orderDetail: data.data[0]
        });
        console.log(that.data.orderDetail)
        var starttime = that.data.orderDetail.UseCarStartTime
        var endtime = that.data.orderDetail.UseCarEndTime

        if (starttime.substring(11, 16) == '00:00' && endtime.substring(11, 16) == '23:59') {
          that.setData({
            UseCarStart: starttime.substring(0, 10),
            UseCarEnd: endtime.substring(0, 10)
          })
        } else {
          that.setData({
            UseCarStart: starttime.substring(0, 16),
            UseCarEnd: endtime.substring(0, 16)
          })
        }

        var arr = that.data.orderDetail
        if (arr.CarCompanyID <= 0)
          that.data.telNum = arr.TravRenTel
        else {
          that.data.telNum = arr.CarCompRenTel
        }

      } else {
        that.setData({
          order_error: true
        });

      }
    },
    fail: function () {
      // fail
      that.setData({
        order_error: true
      });
    },
    complete: function () {
      // complete
      wx.hideToast();
      wx.stopPullDownRefresh();
    }
  })
}

function getDataChengke(that) {
  that.data.chengkedetail = []
  wx.showToast({
    title: '正在加载...',
    icon: 'loading',
    duration: 10000
  });
  var userType = wx.getStorageSync('userType');
  var userInfo = wx.getStorageSync('userInfo');
  wx.request({
    url: 'https://www.lanshuicar.com/Server/GetCarsGuidersCusts.ashx',
    data: {
      IDD: that.data.IDD,
      UID: userInfo.Id,
      UType: userType,
      OType: 1,
      PageSize: 60,
      PageIndex: 1
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    success: function (res) {
      console.log(res);
      var code = res.data.code;
      if (code == 0) {
        if (res.data.data.length > 0) {
          that.setData({
            chengkedetail: res.data.data
          });
          console.log(that.data.chengkedetail)
        } 
      }else{
        that.showError(res.data.msg)
      } 
    },
    fail: function () {
      that.showError(res.data.msg)
    },
    complete: function () {
      wx.hideToast();
    }
  })
}